import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { JhiEventManager } from 'ng-jhipster';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { IReceiveAddr } from 'app/shared/model/receive-addr.model';
import { ReceiveAddrService } from './receive-addr.service';
import { ReceiveAddrDeleteDialogComponent } from './receive-addr-delete-dialog.component';

@Component({
  selector: 'jhi-receive-addr',
  templateUrl: './receive-addr.component.html',
})
export class ReceiveAddrComponent implements OnInit, OnDestroy {
  receiveAddrs?: IReceiveAddr[];
  eventSubscriber?: Subscription;

  constructor(
    protected receiveAddrService: ReceiveAddrService,
    protected eventManager: JhiEventManager,
    protected modalService: NgbModal
  ) {}

  loadAll(): void {
    this.receiveAddrService.query().subscribe((res: HttpResponse<IReceiveAddr[]>) => (this.receiveAddrs = res.body || []));
  }

  ngOnInit(): void {
    this.loadAll();
    this.registerChangeInReceiveAddrs();
  }

  ngOnDestroy(): void {
    if (this.eventSubscriber) {
      this.eventManager.destroy(this.eventSubscriber);
    }
  }

  trackId(index: number, item: IReceiveAddr): number {
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
    return item.id!;
  }

  registerChangeInReceiveAddrs(): void {
    this.eventSubscriber = this.eventManager.subscribe('receiveAddrListModification', () => this.loadAll());
  }

  delete(receiveAddr: IReceiveAddr): void {
    const modalRef = this.modalService.open(ReceiveAddrDeleteDialogComponent, { size: 'lg', backdrop: 'static' });
    modalRef.componentInstance.receiveAddr = receiveAddr;
  }
}
